package com.android.pI;



import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;


public class LogActivity extends Activity {
	private static final int INSERT_ID = Menu.FIRST;
	ListView menuList;
	ListView menu;
	DataBaseHelper dbh;
	Cursor cursor;
	SimpleCursorAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dbh = new DataBaseHelper(this);

		// Setup UI
		setContentView(R.layout.notes_list);
		menuList = (ListView) findViewById(R.id.listNotes);
		fillData();
		menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View itemClicked,
					int position, long id) {
				cursor.moveToPosition(position);
				String logSelected = (String)cursor.getString(0);
				String ename = (String)cursor.getString(2);
				Intent intent = new Intent();// intent is an envelop
				// arg1 is the current class and arg2 is the class to pass to
				intent.setClass(LogActivity.this, LogEditActivity.class);
				// bundle is the letter
				Bundle bundle = new Bundle();
				// arg1 is the keyword for the string , arg2 is the sting to
				// pass
				bundle.putString("log_id", logSelected);
				bundle.putString("ex_name", ename);
				bundle.putInt("case", 1);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});

	}

	private void fillData() {
		// Get the data
		cursor = dbh.fetchLog();
		startManagingCursor(cursor);

		// Setup Adapter
		String[] from = { "ex_name", "date", "reps" };
		int[] to = { R.id.log_ex_name, R.id.log_date, R.id.log_reps };
		adapter = new SimpleCursorAdapter(this, R.layout.notes_row, cursor,
				from, to);
		menuList.setAdapter(adapter);
		dbh.close();
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, "Add New");
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case INSERT_ID:
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

	
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveState();
	}

	@Override
	protected void onPause() {
		super.onPause();
		saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		saveState();
	}

	private void saveState() {
		fillData();
	}

}
